<?php
    //For form to send data
    if(empty($page)) {
	$page = "addIsToSubdivision.php";
    }

    $sql = "SELECT * FROM subdivisions ORDER BY code";
    $subdivisions = mysql_query($sql);

    $sql = "SELECT * FROM information_systems ORDER BY code";
    $information_systems = mysql_query($sql);

    if(!empty($_POST['information_system'])) {
	$subd = mysql_real_escape_string($_POST['subdivision']);
	$date = mysql_real_escape_string($_POST['date']);
	$is = $_POST['information_system'];

	//get existing Is for this subdivision
	for($i = 0; $i < count($is); $i++) {
	    $is[$i] =  mysql_real_escape_string($is[$i]);
	}
	$query = "SELECT is_code FROM is_subdivisions WHERE subdivision_code = '$subd'";
	$is_codes = mysql_query($query);
	
	//select only new Is for this subdivision
	while($i = mysql_fetch_assoc($is_codes)) {
	    if(in_array($i['is_code'], $is)) {
		$key = array_search($i['is_code'], $is);
		unset($is[$key]);
	    }
	}
	if(count($is) > 0) {
	    $sql = "INSERT INTO is_subdivisions (is_code, subdivision_code, date) VALUES ";
	    $first = "";
	    foreach($is as $i) {
		$sql .= "$first('$i', '$subd', '$date')";
		$first = ", ";
	    }
	    mysql_query($sql);
	    print $sql;
	}
    }

    //db_close();
?>

<label for="error" style="color:red;"><?php if(!empty($error_string)) echo $error_string; ?></label>
<label for="inform" style="color:green;"><?php if(!empty($msg)) echo $msg; ?></label>

<form name="IsToSubdivision" action="<?php echo $page;?>" method="POST">
    <label for="subdivision">Padalinys:</label>
    <!-- Subdivisions select box -->
    <select name="subdivision">
	<?php
	    while($subdivision = mysql_fetch_assoc($subdivisions)) {
		print "<option value='$subdivision[code]'>$subdivision[code] : $subdivision[title]</option>";
	    }
	?>
    </select></br>

    <label for="addIs">Pridėti Informacines sistemas(jau esamų nebereikia):</label></br>
    <!-- IS checkbox list -->
    <?php
	while($information_system = mysql_fetch_assoc($information_systems)) {
	    ?>
	    <label for="<?php print $information_system['code']; ?>"><?php print $information_system['code']; ?></label>
	    <input type="checkbox" name="information_system[]" value="<?php print $information_system['code']; ?>"/>
	    <?php
	}
    ?>
    </br>

    <label for="IsAddDate">Is pridėjimo/veiklos pradžios data:</label>
    <input type="" name="date" value="<?php print date("Y-m-d"); ?>"/></br>
    
    <input type="submit" name="submit" value="Susieti"/>
</form>
<a href="index.php?changes">Atgal</a>